package com.ericsson.enap.modules.cmdkpi.thread;

import com.ericsson.common.pojo.InputStreamChannelExec;
import com.ericsson.common.util.EnipSshUtil;
import com.ericsson.enap.modules.cmdkpi.entity.AmfKpiDetail;
import com.ericsson.enap.modules.cmdkpi.entity.CmdKpiDict;
import com.ericsson.enap.modules.cmdkpi.task.CmdKpiTask;
import com.ericsson.enap.modules.sys.entity.EnipNetelement;
import com.jcraft.enipjsch.ChannelExec;
import com.jcraft.enipjsch.JSch;
import com.jcraft.enipjsch.Session;
import org.slf4j.Logger;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: 多线程处理多个网元
 * @author: chenhongbo
 * @create: 2021-09-03 10:12
 */
public class CmdKpiThread implements Runnable {

    private Map<String, CmdKpiDict> dictMap;
    private String collectionName;
    private MongoTemplate mongoTemplate;
    private EnipNetelement newnetelement;
    private Logger log;

    public CmdKpiThread(Map<String, CmdKpiDict> dictMap, String collectionName, MongoTemplate mongoTemplate,
                        EnipNetelement newnetelement,Logger log) {
        this.dictMap = dictMap;
        this.collectionName = collectionName;
        this.mongoTemplate = mongoTemplate;
        this.newnetelement = newnetelement;
        this.log = log;
    }

    @Override
    public void run() {

        Session session = null;
        ChannelExec channelExec = null;
        BufferedReader input = null;
        //EnipSshUtil ssh = null;
        try {


            Calendar cale = Calendar.getInstance();

            JSch jsch = new JSch();
            session = jsch.getSession(newnetelement.getUsername(), newnetelement.getIp4(), 22);
            session.setConfig("StrictHostKeyChecking", "no");
            session.setPassword(newnetelement.getPassword());
            session.connect();
            channelExec =  (ChannelExec) session.openChannel("exec");
            //channelExec.setCommand("pdc_kpi.pl -n 10 -i 5");
            channelExec.setCommand("pdc_kpi.pl -k ~/kpi_descriptions_bak/ -n 5 -i 5");
            channelExec.setInputStream(null);
            input = new BufferedReader(new InputStreamReader(channelExec.getInputStream()));
            channelExec.connect();

            /*File file = new File("F:/amf_pdc_kpi.txt");
            input = new BufferedReader(new FileReader(file));*/


/*            ssh = new EnipSshUtil(newnetelement.getIp4(),newnetelement.getUsername(),newnetelement.getPassword());
            ssh.connect();

            InputStreamChannelExec Isce = ssh.execCommandReturnStream("pdc_kpi.pl -n 10 -i 5");
            input = new BufferedReader(Isce.getIs());*/

            LinkedHashMap<String, AmfKpiDetail> kpiObjectMap = new LinkedHashMap<>();
            String line;
            while ((line = input.readLine()) != null) {
                if (line.contains("NodeType")) {
                    String nodeType = line.substring(line.indexOf("NodeType") + 10);
                    String month = line.substring(7, 10);
                    String payloadUplink = "";
                    String payloadDownlink = "";
                    boolean containsPayload = false;
                    if (line.contains("Payload")) {
                        String[] arr = line.split("\\s{2,}");
                        payloadUplink = arr[1];
                        payloadDownlink = arr[2];
                        containsPayload = true;
                    }
                    String[] kpiKey = null;
                    breakNodeType: while ((line = input.readLine()) != null) {
                        if (line.contains("Day")) {
                            kpiKey = line.split("\\s{2,}");
                            if ((containsPayload) && (line.contains("||"))) {
                                String[] subKpiKey = new String[8];
                                for (int i = 0; i < 8; i++) {
                                    if (i < 2) {
                                        subKpiKey[i] = kpiKey[i];
                                    } else if ((i >= 2) && (i < 5)) {
                                        subKpiKey[i] = (payloadUplink + " " + kpiKey[i]);
                                    } else {
                                        subKpiKey[i] = (payloadDownlink + " " + kpiKey[(i + 1)]);
                                    }
                                }
                                kpiKey = subKpiKey;
                            }
                            while ((line = input.readLine()) != null) {
                                Map<String, Map<String, String>> nodeTypeMap = new LinkedHashMap<>();
                                if (line.contains("Average")) {
                                    break breakNodeType;
                                }
                                String[] kpiVal = line.split("\\s+");
                                if ((kpiVal.length > 1) && (kpiKey != null)) {
                                    if (line.contains("||")) {
                                        List<String> list = new ArrayList(Arrays.asList(kpiVal));
                                        list.remove("||");
                                        String[] newKpiVal = new String[kpiVal.length - 1];
                                        for (int i = 0; i < list.size(); i++) {
                                            newKpiVal[i] = ((String) list.get(i));
                                        }
                                        kpiVal = newKpiVal;
                                    }
                                    Map<String, String> subKpiMap = new LinkedHashMap<>();
                                    for (int i = 0; i < kpiKey.length; i++) {
                                        if ((!"Day".equals(kpiKey[i])) && (!"Time".equals(kpiKey[i]))) {
                                            if(kpiKey[i].contains("Registered Subscribers (SRU)")) {
                                                kpiKey[i] = "Reg_Subs";
                                            }
                                            CmdKpiDict d = (CmdKpiDict) dictMap.get(nodeType + " " + kpiKey[i]);
                                            if(d == null) {
                                                System.out.println(nodeType + " " + kpiKey[i]);
                                            }
                                            String key = String.valueOf(d.getId());
                                            String value = "0";
                                            if("0".equals(d.getCounterType())) {  //%
                                                if("-".equals(kpiVal[i])) {
                                                    value = "100";
                                                } else {
                                                    if(kpiVal[i].contains("%")) {
                                                        value = ""+(100 - Double.valueOf(kpiVal[i].substring(0,kpiVal[i].length()-1)));
                                                    } else {
                                                        log.error("getCounterType 类型不匹配" + kpiVal[i]);
                                                    }
                                                }
                                            } else {
                                                if("-".equals(kpiVal[i])) {
                                                    value = "0";
                                                } else {
                                                    value = kpiVal[i];
                                                }
                                            }
                                            subKpiMap.put(key, value.replaceAll("%",""));
                                           // subKpiMap.put(key, "-".equals(kpiVal[i])?"0":(kpiVal[i].contains("%")?kpiVal[i].substring(0,kpiVal[i].length()-1):kpiVal[i]));
                                        }
                                    }
                                    nodeTypeMap.put(nodeType, subKpiMap);
                                    AmfKpiDetail detail = (AmfKpiDetail) kpiObjectMap.get(kpiVal[1]);
                                    if (detail == null) {
                                        AmfKpiDetail mkd = new AmfKpiDetail();
                                        mkd.setNetid("" + this.newnetelement.getId().intValue());
                                        mkd.setNetName(this.newnetelement.getName());
                                        mkd.setPoolid("" + this.newnetelement.getPool_id());
                                        int year = cale.get(1);
                                        String mon = CmdKpiTask.monthMap.get(month);

                                        String dataStr = year + "-" + mon + "-" + kpiVal[0] + " " + kpiVal[1] + ":00";
                                        mkd.setDateTime(dataStr);
                                        mkd.setNodeKpiMap(nodeTypeMap);
                                        kpiObjectMap.put(kpiVal[1], mkd);
                                    } else {
                                        Map<String, Map<String, String>> subMap = detail.getNodeKpiMap();
                                        Map<String, String> subkpi = subMap.get(nodeType);
                                        if (subkpi == null) {
                                            subMap.putAll(nodeTypeMap);
                                        } else {
                                            subkpi.putAll(subKpiMap);
                                        }
                                    }
                                }
                            }

                        }
                    }

                }
            }

            for (String key : kpiObjectMap.keySet()) {
                AmfKpiDetail detail = kpiObjectMap.get(key);
                Map<String, Map<String, String>> nodeMap = detail.getNodeKpiMap();

                for(String nodeKey:nodeMap.keySet()) {
                    detail.getKpiMap().putAll(nodeMap.get(nodeKey));
                }
                saveMongodb(detail, this.collectionName);
            }

        } catch (Exception e) {
            e.printStackTrace();
            log.error("CmdKpiTask:" + e.getMessage(), e);
        } finally {
            try {
                input.close();
            } catch (IOException e) {
                log.error("input:" + e.getMessage(), e);
                e.printStackTrace();
            }

            if (channelExec != null && !channelExec.isClosed()) {
                channelExec.disconnect();
            }
            if (session != null && session.isConnected()) {
                session.disconnect();
            }
        }
    }

    public void saveMongodb(AmfKpiDetail detail, String collectionName) {
        List<AmfKpiDetail> kdList = this.mongoTemplate.find(
                new Query(Criteria.where("netid").is(detail.getNetid()).and("dateTime").is(detail.getDateTime())),
                AmfKpiDetail.class, collectionName);
        log.info("网元:" + detail.getNetid() + " 时间:" + detail.getDateTime());
        if ((kdList == null) || (kdList.size() <= 0)) {

            //System.out.println(detail.getNetid() + "-------" + detail.getDateTime());
            log.info(detail.getNetid() + "-------" + detail.getDateTime());
            this.mongoTemplate.insert(detail, collectionName);
        }
    }
}
